package com.example.threaddemo618lw;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView tvinfo1,tvinfo2;
    private Button btnstart,btnstop;
    private boolean flag;

    @SuppressWarnings("HandlerLeak")
    private Handler myhandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 1:
                    tvinfo1.setText((String)msg.obj);
                    break;
                case 2:
                    tvinfo2.setText("收到一次消息");
                    break;
            }
            super.handleMessage();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        tvinfo1=findViewById(R.id.textView);
        tvinfo2=findViewById(R.id.textView2);
        btnstart=findViewById(R.id.button);
        btnstop=findViewById(R.id.button2);

        btnstart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=true;
                MyThread thread=new MyThread();
                thread.start();
            }
        });

        btnstop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=false;
            }
        });
    }

    @Override
    protected void onDestroy() {
        flag=false;

        super.onDestroy();
    }


    public class MyThread extends Thread{
        int num=0;

        @Override
        public void run() {
            myhandler.sendEmptyMessage(2);
            while (flag){
                num++;
                Message message=new Message();
                message.what=1;
                message.obj="字符"+num;
                myhandler.sendMessage(message);
                try{
                    Thread.sleep(1000);
                }

            super.run();
        }
    }
}
